package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/user"
	"path/filepath"
	"strconv"
	"time"
)

type Config struct {
	SavePair
}

type Setting struct {
	Path    string
	OutPath string
	Pairs   map[int]SavePair
}

const listConfig = "listV2"

func FormartTime(t time.Time) string {
	return t.Format("2006-01-02 15:04:05")
}

func ToUnix(t time.Time) string {
	itemName := strconv.FormatInt(t.Unix(), 10)
	return itemName
}

func GetListDir(itemName string) string {
	current, _ := user.Current()
	return filepath.Join(current.HomeDir, listConfig, itemName)
}
func GetAllListDir() string {
	current, _ := user.Current()
	return filepath.Join(current.HomeDir, listConfig)
}

func MakeListDir(s string) string {
	dir := GetListDir(s)

	if !fileExists(dir) {
		os.MkdirAll(dir, 0755)
	}

	return dir
}

func InitListConfig() {
	current, err := user.Current()

	if err != nil {
		panic(err)
	}

	listDir := filepath.Join(current.HomeDir, listConfig)

	if !fileExists(listDir) {
		os.MkdirAll(listDir, 0755)
	}
}

func NewSetting() *Setting {
	current, err := user.Current()

	if err != nil {
		panic(err)
	}

	return &Setting{Path: filepath.Join(current.HomeDir, "data.json"), OutPath: filepath.Join(current.HomeDir, "outPath.json")}
}

func fileExists(filename string) bool {
	if _, err := os.Stat(filename); err == nil {
		return true
	}
	return false
}

func (s *Setting) SavePair(data map[int]*PartLine) {
	saveData := []*SavePair{}
	for _, line := range data {
		saveData = append(saveData, NewSavePair(line.Left.Text, line.Right.Text, line.Index))
	}

	marshal, err := json.Marshal(saveData)
	log.Println("保存setting ", string(marshal))
	if err != nil {
		log.Fatal(err)
	}
	file, err := os.OpenFile(s.Path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		log.Fatal(err)
	}

	file.Write(marshal)
}

func (s *Setting) SaveOutPut() {

	data := make(map[string]string)

	data["outExcel"] = bc.OutExcel.Text
	data["outChart"] = bc.OutChart.Text

	marshal, err := json.Marshal(data)
	log.Println("保存outsetting ", string(marshal))
	if err != nil {
		log.Fatal(err)
	}
	file, err := os.OpenFile(s.OutPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		log.Fatal(err)
	}

	file.Write(marshal)
}
func handlePanic() {
	if r := recover(); r != nil {
		fmt.Println("Recovered:", r)
	}
}

func (s *Setting) Loan(c *BtcContext) {
	defer handlePanic()
	file, err := ioutil.ReadFile(s.Path)

	if err != nil {
		log.Println("加载失败")
		return
	}
	bc.Log("加载数据file " + string(file))

	var configData []SavePair

	err = json.Unmarshal(file, &configData)

	c.PairData = configData
	if err != nil {
		panic(err)
	}
	for _, v := range configData {
		line := c.Part[v.Index]

		line.Left.SetText(v.Left)
		line.Right.SetText(v.Right)
	}
}

func (s *Setting) LoanOut() {
	defer handlePanic()
	file, err := ioutil.ReadFile(s.OutPath)

	if err != nil {
		log.Println("加载失败")
		return
	}
	log.Println("加载数据file ", string(file))

	m := make(map[string]string)

	err = json.Unmarshal(file, &m)

	if err != nil {
		panic(err)
	}

	bc.OutExcel.SetText(m["outExcel"])
	bc.OutChart.SetText(m["outChart"])
}

func (s *Setting) loanApiKey() string {
	dir, _ := os.Getwd()
	join := filepath.Join(dir, "apiKey.txt")

	file, err := os.ReadFile(join)

	if err != nil {
		return ""
	}
	return string(file)
}

func (s *Setting) saveApiKey(k string) {
	dir, _ := os.Getwd()
	join := filepath.Join(dir, "apiKey.txt")

	os.WriteFile(join, []byte(k), 0644)
}

type SavePair struct {
	Left  string `json:"left"`
	Right string `json:"right"`
	Index int    `json:"index"`
}

func NewSavePair(left string, right string, index int) *SavePair {
	return &SavePair{Left: left, Right: right, Index: index}
}
